import React, { useEffect } from 'react'
import { Modal, Form, Input, DatePicker, message } from 'antd'
import { getCreatePlan } from '@/api/electricity'

export default function AddPlan(props) {

  const { visible, setVisible, getPlans } = props

  const [messageApi, contextHolder] = message.useMessage()
  const [form] = Form.useForm()

  useEffect(() => {
    !visible && form.resetFields()
  }, [visible])

  const handleOk = () => {
    form.validateFields()
    .then(async values => {
      let {
        'plan-name': planName, 
        'plan-start-time': planST, 
        'plan-end-time': planET, 
        'plan-level': planLevel, 
        'plan-type': planType 
      } = values

      getCreatePlan({
        plan_name: planName,
        start_time: planST.format('YYYY-MM-DD HH:mm:ss'),
        end_time: planET.format('YYYY-MM-DD HH:mm:ss'),
        plan_type: planType,
        plan_level: planLevel
      }).then(res => {
        let type = res.indexOf('成功') > -1 ? 'success' : 'warning'
        messageApi.open({
          type,
          content: res
        })
        if(type === 'success') {
          getPlans(false)
          setVisible(false)
        } 
      })

    }).catch(e => {})
  }

  return <Modal
    title="新建规则"
    open={visible}
    style={{ top: '15%' }}
    width={400}
    onCancel={() => {
      setVisible(false)
    }}
    onOk={handleOk}
  >
    {contextHolder}
    <Form
      name="add-plan-form"
      form={form}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 16 }}
      style={{ maxWidth: 600 }}
      autoComplete="off"
    >
      <Form.Item label="预案名称" name="plan-name" rules={[{ required: true, message: '请填写预案名称' }]}>
        <Input />
      </Form.Item>
      <Form.Item label="起始时间" name="plan-start-time" rules={[
        {required: true, message: '请填写起始时间' },
        {validator: (_, value) => {
          if(!value) return Promise.reject()
          let ve = form.getFieldValue('plan-end-time')
          if(ve && ve.isBefore(value)) {
            return Promise.reject('起始时间不能大于终止时间')
          }
          return Promise.resolve()
        }}
      ]}>
        <DatePicker showTime={true} />
      </Form.Item>
      <Form.Item label="终止时间" name="plan-end-time" rules={[
        { required: true, message: '请填写终止时间' },
        {validator: (_, value) => {
          if(!value) return Promise.reject()
          let vs = form.getFieldValue('plan-start-time')
          if(vs && vs.isAfter(value)) {
            return Promise.reject('终止时间不能小于起始时间')
          }
          return Promise.resolve()
        }}
      ]}>
        <DatePicker showTime={true} />
      </Form.Item>
      <Form.Item label="预案级别" name="plan-level" rules={[{ required: true, message: '请填写预案级别' }]}>
        <Input />
      </Form.Item>
      <Form.Item label="预案类型" name="plan-type" rules={[{ required: true, message: '请填写预案类型' }]}>
        <Input />
      </Form.Item>
    </Form>
  </Modal>

}
